<?php
namespace common\action;

use herosphp\bean\Beans;
use herosphp\core\Controller;
use herosphp\core\WebApplication;
use member\service\LoginService;
use herosphp\core\Loader;
use herosphp\utils\Page;

Loader::import('member.service.LoginService');

define('COM_ERR_MSG', '(⊙o⊙) 系统出了小差！');

/**
 * 前端模块通用 Action
 * @author          horse<314330288@qq.com>
 *为了数据的安全性，此控制器中不对数据库进行操作
 */
abstract class FrontCommonAction extends Controller {

    /**
     * 当前页面
     * @var int
     */
    protected $page = 1;

    /**
     * 没页显示多少条记录
     * @var int
     */
    protected $pagesize = 15;

    /**
     * 查询条件
     * @var string|array
     */
    protected $conditions;

    /**
     * 排序方式
     * @var string|array
     */
    protected $order;

    /**
     * 分组字段
     * @var string
     */
    protected $group;

    /**
     * 分组条件
     * @var string|array
     */
    protected $having;

    /**
     * 查询字段
     * @var string|array
     */
    protected $fields;

    /**
     * 管理员用户
     * @var array
     */
    protected $loginUser;

    /**
     * Beans服务的key
     * @var string
     */
    protected $serviceBean;
    protected $adService = null;
    protected $FreLinkService = null;
    /**
     * 获取登录用户服务
     * @var LoginService
     */
    protected $_user;
    public function C_start()
    {
        parent::C_start();
        //parent::__construct();
        $this->adService = Beans::get("information.informationAd.service");
        $this->FreLinkService = Beans::get("admin.settingFriendlink.service");
        $this->_user = new LoginService();

        $settingService = Beans::get('admin.adminSetting.service');
        $worktimestr = $settingService->getWorktimeStr();
        $qqArr = $settingService->getQa(5);
        $this->assign('qqArr',$qqArr);
        $this->assign('cs_phone',C('cs_phone'));
        $this->assign('pro_unit',C('pro_unit'));
        $this->assign('pro_std',C('pro_std'));
        $this->assign('wx_qr',C('wx_qr'));
        $this->assign('worktimestr',$worktimestr);

        $this->getCertification();
        $this->getSinglepage();
        $this->getSettings();
        $flBotton = $this->FreLinkService->getItems(array('catid'=>$this->friendlink_cate_id('友情链接'),'status'=>1),array(),array('listorder'=>'1'),8);
        $this->assign("FLBotton",$flBotton );//底部友链
        $this->assign("adBotton", $this->adService->getItem(array('ad_place_key'=>"12c65c3744eca390077f0010f27734f7"),array(),array('addtime'=>-1)));
        $this->assign('cartCount',$this->getCartCount());
        $this->assign('remindCount',$this->getRemindCount());


        $app  = WebApplication::getInstance();
        $request = $app->getHttpRequest();
        $module = $request->getModule();
        $action = $request->getAction();
        $method = $request->getMethod();

        //站点关闭，跳转页面
        if(C('site_enabled')=='off'){

            $url = C('site_down_page');

            $url = (strpos($url,'http')===0)?$url:"/{$url}";

            echo "<meta http-equiv='refresh' content='5;URL={$url}'>站点已关闭,5秒后跳转到指定页面！";
            die;
        }

        if($module=='index'&&$action=='index'){
            $this->assign('is_index_page' , '1');
        }else{
            $this->assign('is_index_page' , '0');
        }


        $this->assign('username' , $this->_user->username);
        $this->assign("noRecords", "(⊙o⊙)抱歉，没有找到您要的内容.");
        $request = WebApplication::getInstance()->getHttpRequest();
        $navs = Beans::get('admin.adminNav.service')->getAvailNavCached();
        $this->assign('navs',$navs);
        $currentOpt = $request->getModule() . '/' . $request->getAction() . '/' . $request->getMethod();
        $this->assign('currentOpt',$currentOpt);


        //首页，交易市场，资讯，商品模块方向
        if($module== 'index'||$module=='trading'||$module=='information'||$module=='product'){
            //判断是否已经登陆,把登陆信息记录在头部
            $this->_user = new LoginService();
            if($this->_user->hasLogin())
            {
                $this->assign('userphoto',$this->_user->__get('photo'));
                $this->assign('username' , $this->_user->username);
            }
            return ;
        }
        //登录、注册页放行
        if($action == 'login' || $action == 'reg')
        {
            return ;
        }
        if(!$this->_user->hasLogin())
        {
            header('location:'.url('/member/login/index?dir='.urlencode($_SERVER['REQUEST_URI'])));
            exit(0);
        }

    }


    public function index()
    {
        $this->getSettings();
    }
    public function setDescription($description=null)
    {
        $this->assign('description',$description);
    }
    public function setTitle($title=null)
    {
        $this->assign('title',$title);
    }
    public function setKeyword($keyword=null)
    {
        $this->assign('keywords',$keyword);
    }
    /**
     * @param int $page
     */
    public function setPage($page)
    {
        $this->page = $page;
    }

    /**
     * @return int
     */
    public function getPage()
    {
        return $this->page;
    }

    /**
     * @param int $pagesize
     */
    public function setPagesize($pagesize)
    {
        $this->pagesize = $pagesize;
    }

    /**
     * @return int
     */
    public function getPagesize()
    {
        return $this->pagesize;
    }
    /**
     * 门户交易市场简单分页
     * @param $total 数量
     * @param $isGoto 是否有跳转功能
     * @return string
     */
    public function getSimplePagemenu($total){


        //初始化分页类
        $pageHandler = new Page($total, $this->getPagesize(), $this->getPage(), 3);

        //获取分页数据
        $pageData = $pageHandler->getPageData(DEFAULT_PAGE_STYLE, true);
        //组合分页HTML代码
        $pagemenu = '';

        if ($pageData) {
            $pagemenu .= ' <span class="text">';
            $pagemenu .= ''.$this->getPage().'/' . $pageHandler->pageNum . '';
            $pagemenu .= ' </span>';

            $pagemenu .= '<a class="last link2" href="' . $pageData['prev'] . '"><i></i> </a>';

            $pagemenu .= '<a class="next" href="' . $pageData['next'] . '"><i></i> </a>';


        }
        $this->assign('simplePagemenu', $pagemenu);

    }
    /**
     * 门户交易市场分页
     * @param $total 数量
     * @param $isGoto 是否有跳转功能
     * @return string
     */
    public function getPagemenu($total,$isGoto=1,$tags='款产品'){
        //初始化分页类
        $pageHandler = new Page($total, $this->getPagesize(), $this->getPage(), 3);
        //获取分页数据
        $pageData = $pageHandler->getPageData(DEFAULT_PAGE_STYLE, true);
        //组合分页HTML代码
        $pagemenu = '';

        if ($pageData) {
            $pagemenu = '<nav class="pageBar2">';
            $pagemenu .= '<div class="number">共有'.$pageHandler->pageNum.'页&nbsp;共有' . $total . $tags.'</div>';
            $pagemenu .= '<ul class="list">';
            $pagemenu .= '<li class="first"><a href="' . $pageData['first'] . '">首页</a></li>';

            $pagemenu .= '<li class="prev"><a href="' . $pageData['prev'] . '">上一页</a></li>';
            foreach ($pageData['list'] as $key => $value) {
                if ($key - $this->page > 4) {//省略号
                    $pagemenu .= '<li class="li"><a href="javascript:void(0)">...</a></li> ';
                }
                if ($key == $this->page) {
                    $pagemenu .= '<li class="li"><a class="active">' . $key . '</a></li> ';
                } else {
                    $pagemenu .= '<li class="li"><a href="' . $value . '">' . $key . '</a></li> ';
                }
                if ($this->page - $key > 4) {//省略号
                    $pagemenu .= '<li><a href="javascript:void(0)">...</a></li> ';
                }
            }
            $pagemenu .= '<li class="next"><a href="' . $pageData['next'] . '" >下一页</a></li>';
            $pagemenu .= '<li class="last"><a href="' . $pageData['last'] . '">尾页</a></li>';
            $pagemenu .= '</ul>';
            if($isGoto) {
                $pagemenu .= '<div class="control">';
                $pagemenu .= '<label>跳至 <input type="text" name="tmp_page" class="pageInput" data-max="'.$pageHandler->pageNum.'" value="' . $this->getPage() . '"/> 页</label>';
                $pagemenu .= '<a href="javascript:void(0)" class="btn-info btn-sm js-jump-page">确认</a>';
                $pagemenu .= '</div>';
            }
            $pagemenu .= '</nav>';
        }
        $this->assign('pagemenu', $pagemenu);

    }
    /**
     * 获取用户页尾的单页数据
     * @Author horse
     * @Create 2016-11-17
     * @return singles array 返回多维数组
     */
    public function getSinglepage()
    {
        //获取单页类型
        $singlePageCate = Beans::get('information.informationSinglepageCate.service')->getItems(array(),array(),array("sort_index"=>1),3);
        foreach($singlePageCate as $cate)
        {
            $child = null;
            $singlePage = Beans::get("information.informationSinglepage.service")
                ->getItems(array("cate_id"=>array('$in'=>$cate['id'])),array(),array("sort_index"=>1),7);
            if($singlePage)
            {
                $child = $singlePage;
            }
            $singles[] = array("id"=>$cate['id'],"name"=>$cate['name'],"child"=>$child);
        }
        $this->assign("singles",$singles);
    }

    /**
     *
     */
    public function getCertification()
    {
        $cate_id = $this->friendlink_cate_id("资质认证");
        $items = $this->FreLinkService->getItems(array('catid'=>$cate_id,'status'=>1),array(),array(),5);
        $this->assign('certification',$items);
    }

    /**
     * return array 返回数组
     */
    public function getSettings()
    {
        //加载系统配置
        $service = Beans::get('admin.adminSetting.service');
        $settings = $service->getSettings(array("site_name","title","keywords","description"));
        $this->assign('__settings', $settings);
    }

    /**
     * 获取购物车商品数量
     * @Author horse
     * @Create 2016-11-18
     * @return $count int
     */
    public function getCartCount()
    {
        $cartService = Beans::get('trading.tradingCart.service');
        $count = 0;
        if($this->_user->hasLogin()){
            $member_id = $this->_user->__get('id');
            $item = $cartService->getCarts($member_id);
            $productIdArr = $item['productIdArr']?$item['productIdArr']:array();
            $productIdArr_c = json_decode($_COOKIE['cartInfo']);
            $need_arr = array_diff($productIdArr_c,$productIdArr);
            foreach($need_arr as $v){
                $cartService->addCartProduct($member_id, $v);
            }
            $item = $cartService->getCarts($member_id);
            $productIdArr = $item['productIdArr']?$item['productIdArr']:array();
            setCookie('cartInfo',json_encode($productIdArr),time()+3600*24*365,'/');
            $count = $cartService->CartProductTotal($member_id);
        }else{
            $count = count(json_decode($_COOKIE['cartInfo']));
        }
        return $count;
    }

    public function friendlink_cate_id($cate_name)
    {
        $friendLink = Beans::get("admin.settingFriendlinkCate.service");
        $item = $friendLink->getItem(array('name'=>$cate_name));
        if($item['id']) {
            return $item['id'];
        }else{
            return 0;
        }
    }
    /**
     * 获取用未读消息都是条数
     * @param $memberId
     */
    public function getRemindCount()
    {
        $member_id = $this->_user->id;
        $remindService = Beans::get('message.messageRemind.service');
        $count = $remindService->getRemindTotal($member_id);
        return $count;
    }
}
